<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<link rel="import" href="../../bower_components/google-chart/google-chart.html">
<link rel="import" href="../../bower_components/iron-resizable-behavior/iron-resizable-behavior.html">
<link rel="import" href="../view-app.html">
<link rel="import" href="../style/shared-styles.html">
<script src="../utilizes/formatDate.js"></script>
<dom-module id="view-dashboard-statistics">
  <template>
    <style include="shared-styles app-grid-style">
      :host {
        margin: 10px;
        display: block;
        --app-grid-columns: 1;
        --app-grid-item-height: 50%;
        --square-size: 1rem;
        --square-gap: 3px;
        --week-width: calc(var(--square-size) + var(--square-gap));
      }

      .months {
        grid-area: months;
      }

      .days {
        grid-area: days;
      }

      .squares {
        grid-area: squares;
      }

      .graph {
        display: grid;
        grid-template-areas: "empty months" "days squares";
        grid-template-columns: auto 1fr;
        grid-gap: 10px;
        padding: 20px;
        border: 1px #eeeeee solid;
        margin: 10px;
      }

      .months {
        display: grid;
        grid-template-columns: calc(var(--week-width) * 4)/* Jan */
        calc(var(--week-width) * 5)/* Feb */
        calc(var(--week-width) * 4)/* Mar */
        calc(var(--week-width) * 5)/* Apr */
        calc(var(--week-width) * 4)/* May */
        calc(var(--week-width) * 5)/* Jun */
        calc(var(--week-width) * 4)/* Jul */
        calc(var(--week-width) * 5)/* Aug */
        calc(var(--week-width) * 4)/* Sep */
        calc(var(--week-width) * 5)/* Oct */
        calc(var(--week-width) * 4)/* Nov */
        calc(var(--week-width) * 5)/* Dec */
        ;
      }

      .days,
      .squares {
        display: grid;
        grid-gap: var(--square-gap);
        grid-template-rows: repeat(7, var(--square-size));
      }

      .squares {
        grid-auto-flow: column;
        grid-auto-columns: var(--square-size);
      }

      /* .days li:nth-child(odd) {
            visibility: hidden;
          } */

      .squares li {
        background-color: #EDEDEE;
      }

      .squares li[data-level="0"] {
        background-color: #EDEDEE;
      }

      .squares li[data-level="1"] {
        background-color: #CCE191;
      }

      .squares li[data-level="2"] {
        background-color: #8FC575;
      }

      .squares li[data-level="3"] {
        background-color: #529646;
      }

      .squares li[data-level="4"] {
        background-color: #365F30;
      }

      .squares {
        grid-area: squares;
      }

      .contrib-legend .legend {
        position: relative;
        display: inline-block;
        margin: 10px 5px;
        list-style: none;
      }

      .contrib-legend .legend li {
        display: inline-block;
        width: 10px;
        height: 10px;
      }

      .tooltip {
        position: relative;
        display: inline-block;
      }

      .tooltip .tooltiptext {
        visibility: hidden;
        width: 120px;
        background-color: rgba(0, 0, 0, 0.75);
        color: #fff;
        text-align: center;
        border-radius: 5px;
        padding: 5px 0;
        position: absolute;
        z-index: 1;
        bottom: 150%;
        left: 50%;
        margin-left: -60px;
      }


      .tooltip .tooltiptext::after {
        content: "";
        position: absolute;
        top: 100%;
        left: 50%;
        margin-left: -5px;
        border-width: 5px;
        border-style: solid;
        border-color: black transparent transparent transparent;
      }

      .tooltip:hover .tooltiptext {
        visibility: visible;
      }

      .btn {
        width: 250px;
      }

      google-chart {
        height: auto;
        width: 100%;
      }

      @media (min-width: 360px) and (max-width: 768px) {
        #column {
          width: 100%;
        }
      }
    </style>
    <firebase-auth app-name="smart-mes" id="auth" user="{{user}}"></firebase-auth>
    <firebase-document app-name="smart-mes" id="userData" path="/user/[[user.uid]]" data="{{k}}"></firebase-document>
    <firebase-document app-name="smart-mes" id="historyQuery" path="/data/[[k.key]]/historyData" data="{{historyData}}"></firebase-document>
    <firebase-query app-name="smart-mes" id="commitQuery" path="/data/[[k.key]]/commitData" data="{{commitData}}">
    </firebase-query>
    <app-localstorage-document key="app-lang" data="{{language}}"></app-localstorage-document>
    <ul class="app-grid">
      <li>
        <div class="card" id="chartContainer">
          <h1 class="title">Product Order Statistics</h1>
          <google-chart id="column" type="column" options="[[columnOptions]]" cols='[[columnItems]]' rows='[[rowItems]]'></google-chart>
          <div class="center">
            <paper-button class="btn" on-click="resetOrderStatistic">Reset Order Statistics</paper-button>
          </div>
        </div>
      </li>
      <li>
        <div class="card">
          <h1 class="title">Overall Working Statistics</h1>
          <div class="center">
            <div class="graph">
              <ul class="months">
                <li>Jan</li>
                <li>Feb</li>
                <li>Mar</li>
                <li>Apr</li>
                <li>May</li>
                <li>Jun</li>
                <li>Jul</li>
                <li>Aug</li>
                <li>Sep</li>
                <li>Oct</li>
                <li>Nov</li>
                <li>Dec</li>
              </ul>
              <ul class="days">
                <li>Sun</li>
                <li>Mon</li>
                <li>Tue</li>
                <li>Wed</li>
                <li>Thu</li>
                <li>Fri</li>
                <li>Sat</li>
              </ul>
              <ul class="squares">
                <template is="dom-repeat" items="{{commitData}}">
                  <li class="tooltip" data-level$="[[item.level]]">
                    <span class="tooltiptext">[[item.commit]] commits on [[item.date]]</span>
                  </li>
                </template>
              </ul>
            </div>
            <div class="contrib-legend">
              Low
              <ul class="legend">
                <li style="background-color: #eee" class=""></li>
                <li style="background-color: #c6e48b" class=""></li>
                <li style="background-color: #7bc96f" class=""></li>
                <li style="background-color: #239a3b" class=""></li>
                <li style="background-color: #196127" class=""></li>
              </ul>
              High
            </div>
          </div>
          <div class="center">
            <paper-button class="btn" on-click="resetWorkLevelStatistics">Reset Working Statistics</paper-button>
          </div>
        </div>
      </li>
    </ul>
    <paper-toast id="toastAlert" always-on-top horizontal-align="right" text="{{localize(toastText)}}"></paper-toast>
  </template>
  <script>
    /**
     * @ViewDashboardStatistic
     * @polymer 
     * @extends {Polymer.Element}
     */
    class ViewDashboardStatistic extends Polymer.mixinBehaviors([Polymer.AppLocalizeBehavior, Polymer.IronResizableBehavior],
      Polymer.Element) {
      static get is() {
        return 'view-dashboard-statistics';
      }
      
      static get properties() {
        return {
          language: String,
          historyData: {
            type: Object,
            notify: true
          },
          columnOptions: Object,
          width: Number,
          height: Number,
          rowItems: Array,
          toastText: String,
          columnItems: {
            type: Array,
            value: () => {
              return [{
                "label": "Data",
                "type": "string"
              }, {
                "label": "No. of orders",
                "type": "number"
              }, {
                "type": "string",
                "role": 'style'
              }]

            }
          },
          commitData: {
            type: Array,
            value() {
              return this.commit || [...Array(isLeapYear() ? 366 : 365)].map((_, i) => ({ 'level': 0, 'commit': 0, 'dayno': i + 1, 'date': dateFromDays(i + 1) }));
            }
          }
        }
      }

      connectedCallback() {
        super.connectedCallback();
        this.loadResources(this.resolveUrl('../../data/locales.json'));
        requestAnimationFrame(this._installListeners.bind(this))
      }

      static get observers() {
        return [
          '_groupAndSum(historyData.order)',
        ]
      }

      _installListeners() {
        this.addEventListener('iron-resize', this._setChartSize)
      }

      _setChartSize() {
        this.width = this.$.chartContainer.offsetWidth
        this.height = this.$.chartContainer.offsetHeight
        if (this.width > 0) {
          this.columnOptions = {
            width: this.width,
            height: 500,
            vAxis: {
              "minValue": 0,
              "maxValue": 10
            },
            tooltip: {
              isHtml: true
            },
            legend: {
              position: "none"
            }
          }
          this.$.column.redraw()
        }
      }

      _groupAndSum(productObject) {
        if (!productObject) return
        if (productObject.length <= 0) {
          this.rowItems = [
            ['No Data', 0, '#202020']
          ]
        }
        const products = Object.values(productObject)
        const unique = (v, i, a) => a.indexOf(v) === i
        const productNames = products.map(product => product.order_product).filter(unique)
        const groupByName = productNames.map(name => products.filter(product => product.order_product === name))
        const quantitySum = groupByName.map(group => {
          const sum = group.reduce((total, arr) => total + arr.order_quantity, 0)
          return [group[0].order_product, sum, group[0].product_color]
        })
        this.rowItems = quantitySum
        this.$.column.redraw()
        return quantitySum
      }

      resetOrderStatistic() {
        if (confirm("Are you sure do you want to reset order statistics ?") == true) {
          this.$.historyQuery.ref.child('order').remove()
          this.$.column.redraw()
          this.toastText = "notification-delete-successfully"
          this.$.toastAlert.open()
        }
      }

      resetWorkLevelStatistics() {
        if (confirm("Are you sure do you want to reset work level statistics ?") == true) {
          let t = [...Array(isLeapYear() ? 366 : 365)].map((_, i) => ({ 'level': 0, 'commit': 0, 'dayno': i + 1, 'date': dateFromDays(i + 1) }));
          this.$.commitQuery.ref.set(t)
        }
      }
    }
    customElements.define(ViewDashboardStatistic.is, ViewDashboardStatistic);
  </script>
</dom-module>